package com.googlecode.mailnet.simulation;

import com.googlecode.mailnet.info.MessageFailureType;

import java.util.ArrayDeque;

/**
 * @author Iskander Akishev
 */
class BoundedMessageQueue {

	private final ArrayDeque<Message> queue = new ArrayDeque<Message>();

	/**
	 * Maximum number of <b>packages</b> that fits into the queue.
	 */
	private final int limit;

	/**
	 * Current size of the queue in <b>packages</b>.
	 */
	private int size;

	BoundedMessageQueue(int limit) {
		this.limit = limit;
	}

	boolean offer(Message message) {
		if (size + message.size > limit) {
			return false;
		}
		queue.add(message);
		size += message.size;
		return true;
	}

	public int getLimit() {
		return limit;
	}

	public int getSize() {
		return size;
	}

	Message peek() {
		return queue.peek();
	}

	Message poll() {
		Message message = queue.poll();
		if (message != null) {
			size -= message.size;
		}
		return message;
	}

	public boolean isEmpty() {
		return queue.isEmpty();
	}

	public void dropAllMessages(NodeState location) {
		for (Message message : queue) {
			message.drop(MessageFailureType.NODE_FAILURE, location);
		}
		queue.clear();
		size = 0;
	}
}
